<?php
namespace app\admin\controller;

use think\Controller;

/**
 * 后台登录
 * Class Login
 */
class LoginController extends Controller {

	protected function _initialize() {
		parent::_initialize();
		// 配置
		if (cache('site_config')) {
			$site_config = cache('site_config');
		} else {
			$site_config = db('system')->field('value')->where('name', 'site_config')->find();
			$site_config = unserialize($site_config['value']);
			cache('site_config', $site_config);
		}
		$this->assign('site_config', $site_config);
	}

	/**
	 * 后台登录
	 * @return mixed
	 */
	public function index() {
		return $this->fetch();
	}

	/**
	 * 登录验证
	 * @return string
	 */
	public function login() {
		if ($this->request->isPost()) {
			$data = $this->request->only(array(
				'login_name',
				'login_pwd',
				'verify'
			));
			$validate_result = $this->validate($data, 'Login');
			if ($validate_result !== true) {
				$this->error($validate_result);
			} else {
				$where['login_name'] = $data['login_name'];
				$where['login_pwd'] = md5_salt($data['login_pwd']);
				$user = db('user')->where($where)->find();
				if (!empty($user)) {
					if ($user['status'] != 1) {
						$this->error('当前用户已禁用');
					} else {
						session('ADMIN', $user);
						if($user['id']==0){
							session('city_id', '');
						}else{
							session('city_id', $user['city_id']);
						}
						db('user')->update(array(
							'last_login_time' => time(),
							'last_login_ip' => $this->request->ip(),
							'id' => $user['id'],
							'session_id' => session_id() //更改登录状态
						));
						$this->success('登录成功', 'index/index');
					}
				} else {
					$this->error('用户名或密码错误');
				}
			}
		}
	}

	/**
	 * 退出登录
	 */
	public function logout() {
		session('ADMIN', null);
		$this->success('退出成功', 'login/index');
	}

}
